package org.apoiolivre.server;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apoiolivre.model.Category;
import org.apoiolivre.model.Movement;
import org.apoiolivre.model.MovementKind;

import javax.jdo.PersistenceManager;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class DataService extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");

		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		String description = req.getParameter("desc");
		Double value = new Double(req.getParameter("value"));
		Integer quantity = new Integer(req.getParameter("qtd"));
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		try {

			
			String query = "select from " + Category.class.getName() +" where description == 'other'";
			String query2 = "select from " + MovementKind.class.getName() +" where label == 'debit'";
			Category cat = null;
			MovementKind kind = null;
			try {
				cat = ((List<Category>) pm.newQuery(query).execute()).get(0);
				kind = ((List<MovementKind>) pm.newQuery(query2).execute()).get(0);
			}
			catch (Exception e) {
				resp.getWriter().println("error: "+e.getMessage());
				resp.getWriter().println("-------------------------");
			}
			
			if(cat == null) {
				cat = new Category("other");
				pm.makePersistent(cat);
			}
			
			if(kind == null) {
				kind = new MovementKind("debit");
				pm.makePersistent(kind);
			}
			
			
		Movement movimento = new Movement(user, value, quantity,
				description, cat, kind);

		
			pm.makePersistent(movimento);
			resp.getWriter().println("done");
		} 
		catch (Exception e) {
			resp.getWriter().println("error: "+e.getMessage());
			resp.getWriter().println("-------------------------");
			e.printStackTrace();
		}
		finally {
			pm.close();
		}

	}
}
